package com.ibangnuo.manage.service.commission;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ibangnuo.framework.domain.*;
import com.ibangnuo.framework.domain.request.commission.CommissionCommercialDayRequest;
import com.ibangnuo.framework.domain.request.commission.CommissionRequest;
import com.ibangnuo.framework.model.response.*;
import com.ibangnuo.manage.dao.OrderRepository;
import com.ibangnuo.manage.dao.commission.CommissionMapper;
import com.ibangnuo.manage.dao.commission.CommissionRepository;
import com.ibangnuo.manage.dao.employee.AgentRepository;
import com.ibangnuo.manage.dao.employee.CommercialRepository;
import com.ibangnuo.manage.service.commission.api.CommissionQuery;
import com.ibangnuo.manage.service.commission.api.impl.DayCommissionQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: wwy
 * @Date: 2020-03-12 16:19
 */
@Service
public class CommissionService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private CommissionRepository commissionRepository;
    @Autowired
    private AgentRepository agentRepository;
    @Autowired
    private CommissionMapper commissionMapper;
    @Autowired
    private DayCommissionQuery dayCommissionQuery;
    @Autowired
    private CommercialRepository commercialRepository;


    /**
     * 日佣金统计
     * 1.每天凌晨统计前一天的佣金，并保存到日佣金记录表
     * 2.先统计机具，然后统计商家，最后统计代理商，保存在redis中
     */
    @Scheduled(cron = "* * 1 * * ?")
    public void commissionDayCount(){
        CommissionQuery commissionQuery = new CommissionQuery(dayCommissionQuery);
        commissionQuery.execute();
    }

    /**
     * 下级代理信息
     * 分页查询，首先查询出当前登录人的下级代理，然后in查询
     * @param page
     * @param size
     * @param commissionRequest
     * @return
     */
    public QueryResponseResult findList(int page, int size, CommissionRequest commissionRequest){
        if(commissionRequest == null){
            commissionRequest = new CommissionRequest();
        }
        page = commissionRequest.getPage();
        size = commissionRequest.getSize();

        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Agent agent = agentRepository.findByUserId(user.getId());
        List<Agent> agentList = agentRepository.findByParentIdAndIsDelete(agent.getId(), 1);
        List<String> agentIdList = new ArrayList<>();
        for (Agent agent1 : agentList) {
            agentIdList.add(agent1.getId());
        }
        Map<String,Object> map = new HashMap<>();
        map.put("agentIdList",agentIdList);
        String jsonString = JSONObject.toJSONString(commissionRequest);
        Map requestMap = JSONObject.parseObject(jsonString, Map.class);
        map.putAll(requestMap);
        if(page <= 0){
            page = 1;
        }
        page = page - 1;
        if(size <= 0){
            size = 5;
        }
        PageHelper.startPage(page,size);
        List<CommissionMonth> commissionMonthList = commissionMapper.findListByAgenId(map);
        PageInfo<Map> pageInfo = new PageInfo(commissionMonthList);
        QueryResult queryResult = new QueryResult();
        queryResult.setList(pageInfo.getList());
        queryResult.setTotal(pageInfo.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }

    /**
     * 分页查询日佣金
     * @param page
     * @param size
     * @param commissionRequest
     * @return
     */
    public QueryResponseResult findDayList(int page, int size, CommissionRequest commissionRequest){
        if(commissionRequest == null){
            commissionRequest = new CommissionRequest();
        }
        if(StringUtils.isNotEmpty(commissionRequest.getStartTime())){
            commissionRequest.setStartTime(commissionRequest.getStartTime().substring(0,11));
        }
        if(StringUtils.isNotEmpty(commissionRequest.getEndTime())){
            commissionRequest.setEndTime(commissionRequest.getEndTime().substring(0,11));
        }
        page = commissionRequest.getPage();
        size = commissionRequest.getSize();
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<String> agentIdList = new ArrayList<>();
        agentIdList.add(user.getId());
        Map<String,Object> map = new HashMap<>();
        map.put("agentIdList",agentIdList);
        String jsonString = JSONObject.toJSONString(commissionRequest);
        Map requestMap = JSONObject.parseObject(jsonString, Map.class);
        map.putAll(requestMap);
        if(page <= 0){
            page = 1;
        }
        page = page - 1;
        if(size <= 0){
            size = 5;
        }
        PageHelper.startPage(page,size);
        List<CommissionDay> commissionDayList = commissionMapper.findListDayByAgentId(map);
        PageInfo<Map> pageInfo = new PageInfo(commissionDayList);
        QueryResult queryResult = new QueryResult();
        queryResult.setList(pageInfo.getList());
        queryResult.setTotal(pageInfo.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }

    /**
     * 根据时间范围查询当前代理商的直属商户日佣金统计
     * @param parmMap
     * @return
     */
    public ObjectResult countTimeScope(Map<String,Object> parmMap){
        Map<String, Object> map = commissionMapper.countTimeScope(parmMap);
        return new ObjectResult(CommonCode.SUCCESS,map);
    }

    /**
     * 分页查询根据时间范围和代理商id查询商户日佣金记录
     * @param commissionCommercialDayRequest
     * @return
     */
    public QueryResponseResult findByTimeAndAgentId(CommissionCommercialDayRequest commissionCommercialDayRequest){
        if(commissionCommercialDayRequest == null){
            commissionCommercialDayRequest = new CommissionCommercialDayRequest();
        }
        int page = commissionCommercialDayRequest.getPage();
        int size = commissionCommercialDayRequest.getSize();
        if(page <= 0){
            page = 1;
        }
        page = page - 1;
        if(size <= 0){
            size = 5;
        }
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Agent agent = agentRepository.findByUserId(user.getId());
        List<CommissionCommercialDay> commissionCommercialList = null;
        if(agent.getId().equals(commissionCommercialDayRequest.getAgentId())){
            //登录人查询，只查询自己直属的商户
            PageHelper.startPage(page,size);
            commissionCommercialList = commissionMapper.findByCommercialDay(commissionCommercialDayRequest);

        }

        //不是登录人查询，查询自己代理商商旗下的
        Agent agentOne = this.getAgentById(commissionCommercialDayRequest.getAgentId());

        if("1-2".equals(agent.getHierarchy())){
            //只查询一次
            List<Agent> agentList = agentRepository.findByParentIdAndIsDelete(agentOne.getId(), 1);
            List<String> agentIdList = new ArrayList<>();
            agentIdList.add(agentOne.getId());
            for (Agent agent1 : agentList) {
                agentIdList.add(agent1.getId());
            }
            Map<String,Object> map = new HashMap<>();
            map.put("startTime",commissionCommercialDayRequest.getStartTime());
            map.put("endTime",commissionCommercialDayRequest.getEndTime());
            map.put("list",agentIdList);
            commissionCommercialList = commissionMapper.findByCommercialDayAndAgentId(map);
        }
        if("1-2-3".equals(agent.getHierarchy())){
            //记录为空
        }
        if(commissionCommercialList == null){
            commissionCommercialList = new ArrayList<>();
        }
        PageInfo<CommissionCommercialDay> pageInfo = new PageInfo(commissionCommercialList);
        QueryResult queryResult = new QueryResult();
        queryResult.setList(pageInfo.getList());
        queryResult.setTotal(pageInfo.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);

    }

    /**
     * 根据时间查询当前登录人其下的代理商的商户日佣金统计
     * @param commissionRequest
     * @return
     */
    public QueryResponseResult findByTimeAndParentAgentId(CommissionRequest commissionRequest){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Agent agent = agentRepository.findByUserId(user.getId());
        int page = commissionRequest.getPage();
        int size = commissionRequest.getSize();
        if(page <= 0){
            page = 1;
        }
        page = page - 1;
        if(size <= 0){
            size = 5;
        }

        Map<String,Object> map = new HashMap<>();
        List<Agent> agentList = agentRepository.findByParentIdAndIsDelete(agent.getId(), 1);
        List<String> agentIdList = new ArrayList<>();
        for (Agent agent1 : agentList) {
            agentIdList.add(agent1.getId());
        }
        map.put("list",agentIdList);
        map.put("startTime",commissionRequest.getStartTime());
        map.put("endTime",commissionRequest.getEndTime());
        PageHelper.startPage(page,size);
        List<CommissionDay> commissionDayList = commissionMapper.findByTimeAndParentAgentId(map);
        PageInfo<CommissionDay> pageInfo = new PageInfo<>(commissionDayList);
        QueryResult queryResult = new QueryResult();
        queryResult.setList(pageInfo.getList());
        queryResult.setTotal(pageInfo.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }

    /**
     * 分页查询月佣金
     * @param commissionRequest
     * @return
     */
    public QueryResponseResult findMouthList(CommissionRequest commissionRequest){
        if(commissionRequest == null){
            commissionRequest = new CommissionRequest();
        }
        int page = commissionRequest.getPage();
        int size = commissionRequest.getSize();
        if(page <= 0){
            page = 1;
        }
        page = page - 1;
        if(size <= 0){
            size = 5;
        }
        Map<String,Object> map = new HashMap<>();
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Agent agent = agentRepository.findByUserId(user.getId());
        List<String> agentIdList = new ArrayList<>();
        agentIdList.add(agent.getId());
        map.put("agentIdList",agentIdList);
        String jsonString = JSONObject.toJSONString(commissionRequest);
        Map requestMap = JSONObject.parseObject(jsonString, Map.class);
        map.putAll(requestMap);
        PageHelper.startPage(page,size);
        List<CommissionMonth> commissionMonthList = commissionMapper.findListByAgenId(map);
        PageInfo<CommissionMonth> pageInfo = new PageInfo<>(commissionMonthList);
        QueryResult queryResult = new QueryResult();
        queryResult.setList(pageInfo.getList());
        queryResult.setTotal(pageInfo.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);

    }


    /**
     * 根据时间范围查询当前代理商的直属商户月佣金统计
     * @param parmMap
     * @return
     */
    public ObjectResult countTimeScopeMonth(Map<String,Object> parmMap){
        Map<String, Object> map = commissionMapper.countTimeScopeMonth(parmMap);
        return new ObjectResult(CommonCode.SUCCESS,map);
    }

    /**
     * 根据时间查询当前登录人其下的代理商的商户月佣金统计
     * @param commissionRequest
     * @return
     */
    public QueryResponseResult findByTimeAndParentAgentIdMonth(CommissionRequest commissionRequest){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Agent agent = agentRepository.findByUserId(user.getId());
        int page = commissionRequest.getPage();
        int size = commissionRequest.getSize();
        if(page <= 0){
            page = 1;
        }
        page = page - 1;
        if(size <= 0){
            size = 5;
        }

        Map<String,Object> map = new HashMap<>();
        List<Agent> agentList = agentRepository.findByParentIdAndIsDelete(agent.getId(), 1);
        List<String> agentIdList = new ArrayList<>();
        for (Agent agent1 : agentList) {
            agentIdList.add(agent1.getId());
        }
        map.put("list",agentIdList);
        map.put("startTime",commissionRequest.getStartTime());
        map.put("endTime",commissionRequest.getEndTime());
        PageHelper.startPage(page,size);
        List<CommissionMonth> commissionMonthList = commissionMapper.findByTimeAndParentAgentIdMonth(map);
        PageInfo<CommissionMonth> pageInfo = new PageInfo<>(commissionMonthList);
        QueryResult queryResult = new QueryResult();
        queryResult.setList(pageInfo.getList());
        queryResult.setTotal(pageInfo.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }

    /**
     * 根据时间查询当前登录人其下的代理商的商户月佣金统计
     * @param commissionCommercialDayRequest
     * @return
     */
    public QueryResponseResult findByTimeAndAgentIdMonth(CommissionCommercialDayRequest commissionCommercialDayRequest){
        if(commissionCommercialDayRequest == null){
            commissionCommercialDayRequest = new CommissionCommercialDayRequest();
        }
        int page = commissionCommercialDayRequest.getPage();
        int size = commissionCommercialDayRequest.getSize();
        if(page <= 0){
            page = 1;
        }
        page = page - 1;
        if(size <= 0){
            size = 5;
        }
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Agent agent = agentRepository.findByUserId(user.getId());
        List<CommissionCommercialMonth> commissionCommercialList = null;
        if(agent.getId().equals(commissionCommercialDayRequest.getAgentId())){
            //登录人查询，只查询自己直属的商户
            PageHelper.startPage(page,size);
            commissionCommercialList = commissionMapper.findByCommercialMonth(commissionCommercialDayRequest);

        }

        //不是登录人查询，查询自己代理商商旗下的
        Agent agentOne = this.getAgentById(commissionCommercialDayRequest.getAgentId());

        if("1-2".equals(agent.getHierarchy())){
            //只查询一次
            List<Agent> agentList = agentRepository.findByParentIdAndIsDelete(agentOne.getId(), 1);
            List<String> agentIdList = new ArrayList<>();
            agentIdList.add(agentOne.getId());
            for (Agent agent1 : agentList) {
                agentIdList.add(agent1.getId());
            }
            Map<String,Object> map = new HashMap<>();
            map.put("startTime",commissionCommercialDayRequest.getStartTime());
            map.put("endTime",commissionCommercialDayRequest.getEndTime());
            map.put("list",agentIdList);
            commissionCommercialList = commissionMapper.findByCommercialMonthAndAgentId(map);
        }
        if("1-2-3".equals(agent.getHierarchy())){
            //记录为空
        }
        if(commissionCommercialList == null){
            commissionCommercialList = new ArrayList<>();
        }
        PageInfo<CommissionCommercialDay> pageInfo = new PageInfo(commissionCommercialList);
        QueryResult queryResult = new QueryResult();
        queryResult.setList(pageInfo.getList());
        queryResult.setTotal(pageInfo.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }

    /**
     * 根据id查询商户
     * @param id
     * @return
     */
    private Agent getAgentById(String id){
        Optional<Agent> optional = agentRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    /**
     * 根据代理商id和时间查询月佣金统计
     * @return
     */
    public QueryResponseResult findByAgentIdAndTimeMonth(CommissionRequest commissionRequest){
        int page = commissionRequest.getPage();
        int size = commissionRequest.getSize();
        if(page <= 0){
            page = 1;
        }
        page = page - 1;
        if(size <= 0){
            size = 5;
        }
        PageHelper.startPage(page,size);
        List<CommissionMonth> commissionMonthList = commissionMapper.findByAgentIdAndTimeMonth(commissionRequest);
        List<CommissionDay> commissionMonthList2 = new ArrayList<>();
        for (CommissionMonth commissionMonth : commissionMonthList) {
            CommissionDay commissionDay2 = new CommissionDay();
            String monthDate = commissionMonth.getMonthDate();
            Map<String,Object> parmMap = new HashMap<>();
            parmMap.put("agentId",commissionMonth.getAgentId());
            parmMap.put("startTime",monthDate);
            parmMap.put("endTime",monthDate);
            Map<String, Object> map = commissionMapper.countTimeScopeMonth(parmMap);
            int aliPay = Integer.parseInt(map.get("aliPay")+"");
            int wxPay = Integer.parseInt(map.get("wxPay")+"");
            int thirdParty = Integer.parseInt(map.get("thirdParty")+"");
            int sum = Integer.parseInt(map.get("sum")+"");
            commissionDay2.setMonthDate(commissionMonth.getMonthDate());
            commissionDay2.setWxPay(commissionMonth.getWxPay()-wxPay);
            commissionDay2.setAliPay(commissionMonth.getAliPay()-aliPay);
            commissionDay2.setThirdParty(commissionMonth.getThirdParty()-thirdParty);
            commissionDay2.setSum(commissionMonth.getSum()-sum);
            commissionDay2.setCreateTime(commissionMonth.getCreateTime());
            commissionDay2.setAgentId(commissionMonth.getAgentId());
            commissionMonthList2.add(commissionDay2);

        }
        PageInfo<CommissionDay> pageInfo = new PageInfo<>(commissionMonthList2);

        QueryResult queryResult = new QueryResult();
        queryResult.setTotal(pageInfo.getTotal());
        queryResult.setList(pageInfo.getList());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }


    /**
     * 根据代理商id和时间查询日佣金统计
     * @return
     */
    public QueryResponseResult findByAgentIdAndTimeDay(CommissionRequest commissionRequest){
        int page = commissionRequest.getPage();
        int size = commissionRequest.getSize();
        if(page <= 0){
            page = 1;
        }
        page = page - 1;
        if(size <= 0){
            size = 5;
        }
        PageHelper.startPage(page,size);
        List<CommissionDay> commissionDayList = commissionMapper.findByAgentIdAndTimeDay(commissionRequest);
        List<CommissionDay> commissionDayList2 = new ArrayList<>();
        for (CommissionDay commissionDay : commissionDayList) {
            CommissionDay commissionDay2 = new CommissionDay();
            String monthDate = commissionDay.getMonthDate();
            Map<String,Object> parmMap = new HashMap<>();
            parmMap.put("agentId",commissionDay.getAgentId());
            parmMap.put("startTime",monthDate);
            parmMap.put("endTime",monthDate);
            Map<String, Object> map = commissionMapper.countTimeScope(parmMap);
            int aliPay = Integer.parseInt(map.get("aliPay")+"");
            int wxPay = Integer.parseInt(map.get("wxPay")+"");
            int thirdParty = Integer.parseInt(map.get("thirdParty")+"");
            int sum = Integer.parseInt(map.get("sum")+"");
            commissionDay2.setMonthDate(commissionDay.getMonthDate());
            commissionDay2.setWxPay(commissionDay.getWxPay()-wxPay);
            commissionDay2.setAliPay(commissionDay.getAliPay()-aliPay);
            commissionDay2.setThirdParty(commissionDay.getThirdParty()-thirdParty);
            commissionDay2.setSum(commissionDay.getSum()-sum);
            commissionDay2.setCreateTime(commissionDay.getCreateTime());
            commissionDay2.setAgentId(commissionDay.getAgentId());
            commissionDayList2.add(commissionDay2);

        }
        PageInfo<CommissionDay> pageInfo = new PageInfo<>(commissionDayList2);
        QueryResult queryResult = new QueryResult();
        queryResult.setTotal(pageInfo.getTotal());
        queryResult.setList(pageInfo.getList());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }

    /**
     * 根据id查询月佣金总结
     * @param id
     * @return
     */
    public ObjectResult findMonthById(String id){
        Optional<CommissionMonth> optional = commissionRepository.findById(id);
        if(optional.isPresent()){
            return new ObjectResult(CommonCode.SUCCESS,optional.get());
        }
        return new ObjectResult(CommonCode.FAIL,null);
    }

    /**
     * 根据id修改月佣金
     * @param id
     * @param commissionMonth
     * @return
     */
    public ResponseResult updateMonthById(String id,CommissionMonth commissionMonth){
        CommissionMonth one = this.getMonthById(id);
        if(one != null){
            one.setAliPay(commissionMonth.getAliPay());
            one.setSum(commissionMonth.getSum());
            one.setThirdParty(commissionMonth.getThirdParty());
            one.setWxPay(commissionMonth.getWxPay());
            one.setStatus(1);
            one.setRemark(commissionMonth.getRemark());
            commissionRepository.save(one);
            return new ResponseResult(CommonCode.SUCCESS);
        }
        return new ResponseResult(CommonCode.FAIL);
    }

    /**
     * 根据id查询月佣金
     * @param id
     * @return
     */
    private CommissionMonth getMonthById(String id){
        Optional<CommissionMonth> optional = commissionRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    /**
     * 下级代理信息
     * 分页查询，首先查询出当前登录人的下级代理，然后in查询
     * @param page
     * @param size
     * @param commissionRequest
     * @return
     */
    public QueryResponseResult findListNotStatus(int page, int size, CommissionRequest commissionRequest){
        if(commissionRequest == null){
            commissionRequest = new CommissionRequest();
        }
        page = commissionRequest.getPage();
        size = commissionRequest.getSize();

        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Agent agent = agentRepository.findByUserId(user.getId());
        List<Agent> agentList = agentRepository.findByParentIdAndIsDelete(agent.getId(), 1);
        List<String> agentIdList = new ArrayList<>();
        for (Agent agent1 : agentList) {
            agentIdList.add(agent1.getId());
        }
        Map<String,Object> map = new HashMap<>();
        map.put("agentIdList",agentIdList);
        String jsonString = JSONObject.toJSONString(commissionRequest);
        Map requestMap = JSONObject.parseObject(jsonString, Map.class);
        map.putAll(requestMap);
        if(page <= 0){
            page = 1;
        }
        page = page - 1;
        if(size <= 0){
            size = 5;
        }
        PageHelper.startPage(page,size);
        List<CommissionMonth> commissionMonthList = commissionMapper.findListByAgenIdNotStatus(map);
        PageInfo<Map> pageInfo = new PageInfo(commissionMonthList);
        QueryResult queryResult = new QueryResult();
        queryResult.setList(pageInfo.getList());
        queryResult.setTotal(pageInfo.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }



}
